package com.terrace.controller.system;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.terrace.core.common.model.ResultData;
import com.terrace.db.system.mapper.entity.Organization;
import com.terrace.db.system.mapper.entity.User;
import com.terrace.db.system.mapper.entity.UserOrganization;
import com.terrace.db.system.service.OrganizationService;
import com.terrace.db.system.service.UserService;
import com.terrace.core.mybatis.entity.Pagination;
import com.terrace.core.utils.ApplicationContextUtil;
import com.terrace.core.utils.UUIDGenerator;
import com.terrace.web.annotation.Logs;
import com.terrace.web.constant.GlobalsConstant;
import com.terrace.web.model.DataGrid;

/**
 * 组织机构
 * @author jiangyg
 *
 */
@Controller
@Scope("prototype")
@RequestMapping("/organization")
public class OrganizationController {
	
	private static final String MESSAGE_TYPE = "组织机构";
	
	@Autowired
	private OrganizationService organizationService;
	
	/**
	 * 默认管理页面
	 * @param request
	 * @return
	 */
	@RequestMapping
	public ModelAndView organizationList(HttpServletRequest request){
		return new ModelAndView("system/organization/organizationList");
	}
	
	/**
	 * 组织机构下的用户列表页面
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "userList")
	public ModelAndView userList(@RequestParam("orgId") String orgId, HttpServletRequest request){
		request.setAttribute("orgId", orgId);
		return new ModelAndView("system/organization/userList");
	}
	
	/**
	 * 跳转到添加已存在用户界面
	 * @param roleId
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "addUser")
	public ModelAndView addUser(@RequestParam("orgId") String orgId, HttpServletRequest request){
		request.setAttribute("orgId", orgId);
		return new ModelAndView("system/organization/addUser");
	}
	
	/**
	 * 数据表格
	 * @param request
	 * @param pagination
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "datagrid")
	@RequiresPermissions("system:organization:view")
	public DataGrid<Organization> datagrid(Organization organization, Pagination<Organization> pagination, HttpServletRequest request) {
		DataGrid<Organization> dataGrid = new DataGrid<Organization>();
		dataGrid.setPagination(organizationService.selectOrganizationForPagination(pagination, organization));
		return dataGrid;
	}
	
	/**
	 * 新增或者修改页面
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(@RequestParam(value = "id", required = false) String organizationId, HttpServletRequest request) {
		if (StringUtils.isNotBlank(organizationId)) {
			Organization organization = organizationService.selectOrganizationById(organizationId);
			request.setAttribute("organization", organization);
		}
		return new ModelAndView("system/organization/organization");
	}
	
	/**
	 * 保存组织机构
	 * @param organization
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequestMapping(params = "saveOrUpdate")
	@RequiresPermissions("system:organization:save")
	@Logs(depict = "组织机构保存", type = GlobalsConstant.LogTypes.SYS_ORG)
	public ResultData saveOrUpdate(Organization organization, HttpServletRequest request) {
		ResultData rd = new ResultData();
		if (StringUtils.isBlank(organization.getId())) {
			organization.setId(UUIDGenerator.generate());
			organizationService.saveOrganizationSelective(organization);
			rd.successObjs("10001", MESSAGE_TYPE);
		} else {
			Organization temp = organizationService.selectOrganizationById(organization.getId());
			if (temp == null) {
				return rd.failObjs("13103", MESSAGE_TYPE);
			}
			organizationService.updateOrganizationByIdSelective(organization);
			rd.successObjs("10002", MESSAGE_TYPE);
		}
		return rd;
	}
	
	/**
	 * 用户添加到组织下
	 * @param userId
	 * @param orgId
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequestMapping(params = "userAddOrg")
	@RequiresPermissions("system:user:add:org")
	@Logs(depict = "用户添加到组织下", type = GlobalsConstant.LogTypes.SYS_ROLE)
	public ResultData userAddOrg(@RequestParam("userId") String userId, 
			@RequestParam("orgId") String orgId, HttpServletRequest request) {
		ResultData rd = new ResultData();
		UserService userService = ApplicationContextUtil.getContext().getBean(UserService.class);
		Organization org = organizationService.selectOrganizationById(orgId);
		User user = userService.selectUserById(userId);
		if (user == null || org == null) {
			return rd.failObjs("13105");
		}
		UserOrganization userOrganization = new UserOrganization();
		userOrganization.setId(UUIDGenerator.generate());
		userOrganization.setOrganization(org);
		userOrganization.setUser(user);
		organizationService.saveUserOrganization(userOrganization);
		rd.setMessage("用户[" + user.getUserAccount() + "]新增到[" + org.getOrgName() + "]成功。");
		return rd;
	}
	
	/**
	 * 删除组织下的用户
	 * @param orgId
	 * @param userId
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "deleteUserOnOrg")
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequiresPermissions("system:useronorg:delete")
	@Logs(depict = "删除组织下的用户", type = GlobalsConstant.LogTypes.SYS_ORG)
	public ResultData deleteUserOnOrg(@RequestParam(value = "orgId") String orgId,
			@RequestParam(value = "userId") String userId, HttpServletRequest request) {
		ResultData rd = new ResultData();
		organizationService.deleteUserOrganizationById(userId, orgId);
		return rd.success("删除组织下的用户成功");
	}
	
	/**
	 * 删除组织机构
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(params = "delete")
	@RequiresRoles(GlobalsConstant.Roles.ADMIN)
	@RequiresPermissions("system:organization:delete")
	@Logs(depict = "删除组织机构", type = GlobalsConstant.LogTypes.SYS_ORG)
	public ResultData delete(@RequestParam(value = "id") String organizationId, HttpServletRequest request) {
		ResultData rd = new ResultData();
		Organization organization = organizationService.selectOrganizationById(organizationId);
		if (organization == null) {
			return rd.failObjs("13103", MESSAGE_TYPE);
		}
		
		// 机构中是否存在用户
		UserService userService = ApplicationContextUtil.getContext().getBean(UserService.class);
		Pagination<User> pagination = new Pagination<User>();
		Organization queryOrg = new Organization();
		queryOrg.setId(organizationId);
		userService.selectUsersInOrgForPagination(pagination, new User(), queryOrg);
		if (pagination.getTotal() > 0) {
			return rd.fail("机构[" + organization.getOrgName() + "]已存在用户，要想删除该机构请先删除其下的用户！");
		}
		
		int result = organizationService.deleteOrganizationById(organizationId);
		if (result != 1) {
			rd.failObjs("13102", MESSAGE_TYPE);
		} else {
			rd.successObjs("10003", MESSAGE_TYPE);
		}
		return rd;
	}

}
